package uk.co.accolade.clash.core;

import uk.co.accolade.clash.multicast.Broadcaster;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LocalChangesHandler implements ChangeHandler {

    private static final Log LOG = LogFactory.getLog( LocalChangesHandler.class );

    private ChangesRegistry changesRegistry;
    private Broadcaster broadcaster;

    public LocalChangesHandler( ChangesRegistry changesRegistry,
                                Broadcaster broadcaster ) {
        this.changesRegistry = changesRegistry;
        this.broadcaster = broadcaster;
    }

    public void handleChanges( UserChanges localChanges ) {
        if( changesRegistry.changesAreLocal(localChanges)) {
            changesRegistry.applyChanges( localChanges );
            sendChanges( localChanges );
        }
    }

    private void sendChanges( UserChanges localChanges ) {
        try {
            broadcaster.sendChange( localChanges );
        } catch( IOException e ) {
            LOG.error( e.getMessage(), e );
        }
    }
}